package com.dk.ws;

import com.dk.service.serviceImpl.ChatServiceImpl;
import com.dk.util.DateUtil;
import com.dk.util.JsonUtil;
import com.dk.ws.bean.Message;
import com.dk.ws.bean.ReceiveMessage;
import com.jack.weChatSecurity.core.SecurityHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChatServer extends TextWebSocketHandler {

    private static String ONLINE="[];'./";
    private static String OFFLINE="/.';][";

    @Autowired
    private ChatServiceImpl chatService;
    //客户端<uid,>
    private static Map<String,WebSocketSession> clients=new HashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String id=SecurityHelper.getWeChatUser().getId();
        clients.put(id,session);
        
        //广播上线通知
        broadcast(id, BROADCAST.ONLINE);

        //处理离线消息
        if(chatService.checkHaseOfflineMessage(id)){
            List<Message> offlineMessage = chatService.getOfflineMessage(id);
            for(Message message:offlineMessage){
                session.sendMessage(new TextMessage(JsonUtil.getJsonByObject(message)));
            }
            chatService.updateOfflineMessage(id);
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload=message.getPayload();
        ReceiveMessage receiveMessage=JsonUtil.getObjectByJson(payload, ReceiveMessage.class);
        String sourceId=receiveMessage.getSourceId();
        String destinationId=receiveMessage.getDestinationId();
        String msg= receiveMessage.getMessage();
        Timestamp time=DateUtil.getTimestamp();

        //自己给自己发消息
        if(sourceId.equals(destinationId)){
            chatService.saveChatRecord(sourceId,destinationId,msg,time,1);
        }else{
            //其他人则转发消息
            if(clients.containsKey(destinationId)){
                WebSocketSession target=clients.get(destinationId);
                Message m;
                //判断是否为上线通知
                if(msg.equals(BROADCAST.ONLINE)){
                    m=new Message(sourceId,msg,time,2);
                }
                //正常转发信息
                else{
                    m=new Message(sourceId,msg,time,1);
                    //记录信息
                    //chatService.saveChatRecord();
                }
                target.sendMessage(new TextMessage(JsonUtil.getJsonByObject(m)));
            }
            //存放离线消息
            else{
                chatService.saveChatRecord(sourceId,destinationId,msg,time,0);
            }
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println(exception.toString());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String id=SecurityHelper.getWeChatUser().getId();
        broadcast(id, BROADCAST.OFFLINE);
        clients.remove(id);
    }

    private void broadcast(String id, BROADCAST broadcast) throws IOException {
        List<String> chatPeople = chatService.getChatPeople(id);
        Message message=new Message();
        message.setSourceId(id);
        message.setMessage(broadcast.value);
        message.setTime(DateUtil.getTimestamp());
        message.setWho(2);
        for(String destinationId:chatPeople){
            if(clients.containsKey(destinationId)) {
                clients.get(destinationId).sendMessage(new TextMessage(JsonUtil.getJsonByObject(message)));
            }
        }
    }

    enum BROADCAST{
        OFFLINE(ChatServer.OFFLINE),ONLINE(ChatServer.ONLINE);

        private String value;

        private BROADCAST(String value){
            this.value=value;
        }
    }
}
